package cars

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/cars"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
    carsReq "github.com/flipped-aurora/gin-vue-admin/server/model/cars/request"
)

type CarService struct {
}

// CreateCar 创建car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService) CreateCar(car *cars.Car) (err error) {
	err = global.GVA_DB.Create(car).Error
	return err
}

// DeleteCar 删除car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService)DeleteCar(car cars.Car) (err error) {
	err = global.GVA_DB.Delete(&car).Error
	return err
}

// DeleteCarByIds 批量删除car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService)DeleteCarByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]cars.Car{},"id in ?",ids.Ids).Error
	return err
}

// UpdateCar 更新car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService)UpdateCar(car cars.Car) (err error) {
	err = global.GVA_DB.Save(&car).Error
	return err
}

// GetCar 根据id获取car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService)GetCar(id uint) (car cars.Car, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&car).Error
	return
}

// GetCarInfoList 分页获取car表记录
// Author [piexlmax](https://github.com/piexlmax)
func (carService *CarService)GetCarInfoList(info carsReq.CarSearch) (list []cars.Car, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&cars.Car{})
    var cars []cars.Car
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.CarNumber != "" {
        db = db.Where("car_number = ?",info.CarNumber)
    }
    if info.OwnerName != "" {
        db = db.Where("owner_name = ?",info.OwnerName)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	if limit != 0 {
       db = db.Limit(limit).Offset(offset)
    }
	
	err = db.Find(&cars).Error
	return  cars, total, err
}
